package com.brian.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-07-11 09
 **/
@Component
//rabbitmq中的fanout类型的交换机为发布订阅的模式
//对于已经创建的队列，如果之前没有绑定死信队列，不能做更改绑定死信队列和死信交换机
public class FanoutConfig {

    // 邮件队列
    private String FANOUT_EMAIL_QUEUE = "fanout_email_queue";
    // 短信队列
    private String FANOUT_SMS_QUEUE = "fanout_sms_queue";
    // 交换机名称
    private String EXCHANGE_NAME = "fanoutExchange";

    /**
     * 定义短信队列的死信队列相关信息
     */
    public final static String deadQueueName = "dead_fanout_sms_queue";
    public final static String deadRoutingKey = "dead_sms_routing_key";
    public final static String deadExchangeName = "dead_sms_exchange";
    /**
     * 死信队列 交换机标识符
     */
    public static final String DEAD_LETTER_QUEUE_KEY = "x-dead-letter-exchange";
    /**
     * 死信队列交换机绑定键标识符
     */
    public static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key";



    //定义邮件队列
    @Bean
    public Queue fanOutEmailQueue() {
        return new Queue(FANOUT_EMAIL_QUEUE);
    }

    //定义短信队列
    @Bean
    public Queue fanOutSmsQueue() {
        // 将短信队列绑定到死信队列交换机上
        Map<String, Object> args = new HashMap<>(2);
        args.put(DEAD_LETTER_QUEUE_KEY, deadExchangeName);
        args.put(DEAD_LETTER_ROUTING_KEY, deadRoutingKey);
        Queue queue = new Queue(FANOUT_SMS_QUEUE, true, false, false, args);
        return queue;

    }

    //定义交换机
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange(EXCHANGE_NAME);
    }

    //邮件队列绑定交换机
    @Bean
    public Binding bindingExchangeEmail(Queue fanOutEmailQueue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanOutEmailQueue).to(fanoutExchange);
    }

    // 短信队列绑定交换机
    @Bean
    public Binding bindingExchangeSms(Queue fanOutSmsQueue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanOutSmsQueue).to(fanoutExchange);
    }

    //投递数据转换成json格式的数据
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 配置死信队列
     *
     * @return
     */
    //定义死信队列
    @Bean
    public Queue deadQueue() {
        Queue queue = new Queue(deadQueueName, true);
        return queue;
    }

    //定义死信交换机
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange(deadExchangeName);
    }
    //绑定routingKey
    @Bean
    public Binding bindingDeadExchange(Queue deadQueue, DirectExchange deadExchange) {
        return BindingBuilder.bind(deadQueue).to(deadExchange).with(deadRoutingKey);
    }

}
